package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.OrderEvent;
import com.atguigu.flink.chapter07.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/7/7 9:05
 */
public class Flink06_High_Project_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new OrderEvent(
                    Long.valueOf(data[0]),
                    data[1],
                    data[2],
                    Long.parseLong(data[3]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((order, ts) -> order.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId)
            .window(EventTimeSessionWindows.withGap(Time.minutes(30)))
            .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
    
                private ValueState<OrderEvent> createState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void process(Long orderId,
                                    Context ctx,
                                    Iterable<OrderEvent> elements,
                                    Collector<String> out) throws Exception {
                    // 异常情况出现的时候, 窗口内一定是一个元素
                    List<OrderEvent> list = AtguiguUtil.toList(elements);
                    if (list.size() == 1) {
                        OrderEvent event = list.get(0);
                        
                        // 判断这个是否为create, 如果是则把create放入状态
                        // 如果是pay',则判断去状态是否有create, 如果有: 超时支付 否则就是只有pay没有create
                        if ("create".equals(event.getEventType())) {
                            createState.update(event);
                        }else{
                            OrderEvent create = createState.value();
    
                            if (create != null) {
                                out.collect(event.getOrderId() + " 超时支付, 请检查系统是否正常...");
                            }else{
                                out.collect(event.getOrderId() + " 只有pay,没有create, 请检查系统是否正常...");
                            }
                        }
                    }
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
